import re
import random
import socket
import urllib
import urllib2

from BeautifulSoup import BeautifulSoup

from django.core.management.base import BaseCommand

from mobile.models import CAPVPuerto, Provincia, Carretera

class Command(BaseCommand):
    help = "Sniff Puertos CAPV"
    
    requires_model_validation = True
    
    def handle(self, *app_labels, **options):
        #Get site
        ff_version = "%s.%s.%s.%s" % tuple([random.randint(0,3) for i in range(4)])
        user_agent = "Mozilla/5.0 (Windows; U; Windows NT 5.0; en-GB; rv:1.8.1.4) Gecko/20070515 Firefox/%s" % ff_version #CAPV no te enfades con Firefox
        url = "http://www.trafikoa.net/public/wps/portal/trafico/kcxml/04_Sj9SPykssy0xPLMnMz0vM0Y_QjzKLd4s3cjcHSZnFO8ZbeulHogt5IoR8PfJzU_WD9L31A_QLckMjyh0dFQEAU64A/delta/base64xml/L3dJdyEvd0ZNQUFzQUMvNElVRS82X0ZfMkc1"
        headers = { 'User-Agent' : user_agent }
        socket.setdefaulttimeout(10)
        req = urllib2.Request(url, None, headers)
        response = urllib2.urlopen(req)
        data = response.read()
    
        #Process
        soup = BeautifulSoup(data)
        soup = soup.findAll('tr')
        
        for row in soup:
            tds = row.findAll('td')
            if len(tds) == 10:
                obj_puerto = unicode(tds[0].string)
                obj_puerto = obj_puerto.replace('\n','')
                
                puerto = CAPVPuerto()
                puerto.name = obj_puerto
                puerto.label = obj_puerto.lower()
                puerto.red = unicode(tds[6].string)
                provincia, created = Provincia.objects.get_or_create(name=unicode(tds[1].string))
                puerto.provincia = provincia
                carretera, created = Carretera.objects.get_or_create(name=unicode(tds[7].string))
                puerto.carretera = carretera
                
                if puerto.name != 'Puerto' and puerto.name != 'Tramo' and puerto.name != 'Carretera':
                    puerto.save()
                